/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.etop.ondoc.controller;

import com.etop.ondoc.beans.Category;
import com.etop.ondoc.beans.Document;
import com.etop.ondoc.beans.User;
import com.etop.ondoc.dao.BCategoryDao;
import com.etop.ondoc.dao.BDocDao;
import com.etop.ondoc.dao.BUserDao;
import com.etop.ondoc.dao.DaoFactory;
import com.etop.ondoc.dao.DocumentDao;
import com.etop.ondoc.dao.UserDao;
import com.etop.ondoc.dto.ModifyInputDTO;
import com.etop.ondoc.util.DefaultValue;
import com.etop.ondoc.util.MD5;
import com.etop.ondoc.util.OndocException;
import com.etop.ondoc.util.Thumb;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author jansing lz_jansing@163.com
 */
@Controller
@SessionAttributes("loginUser")
public class UserController {

    private UserDao ud = DaoFactory.getUserDao();
    private DocumentDao docuDao = DaoFactory.getDocumentDao();
    private BDocDao bdd = BDocDao.getInstance();
    private BUserDao bud = BUserDao.getInstance();
    private BCategoryDao bcd = BCategoryDao.getInstance();

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(ModifyInputDTO user, HttpSession session) {
        //判断是否禁用JS
        if (user.getUsername() == null || "".equals(user.getUsername().trim())
                || user.getPassword() == null || "".equals(user.getPassword().trim())) {
            throw new OndocException("尊敬的用户您好，由于本系统的大量功能由JS实现，请取消禁用JS脚本");
        }

        User tempUser = ud.loadByUsername(user.getUsername());
//            User tempUser = DaoFactory.getUserDao().loadByUsername(formUser.getUsername());
        if (tempUser == null || tempUser.getIsVaild() == User.IS_NOT_VAILD
                || !new MD5().getkeyBeanofStr(user.getPassword()).equals(tempUser.getPassword())) {
            throw new OndocException("尊敬的用户您好，由于本系统的大量功能由JS实现，请取消禁用JS脚本");
        }
        session.setAttribute("loginUser", tempUser);
        return "redirect:main";
    }

    @RequestMapping(value = "/regist", method = RequestMethod.POST)
    public String regist(ModifyInputDTO user) {
        //判断是否禁用JS
        if (user.getUsername() == null || "".equals(user.getUsername().trim())
                || user.getPassword() == null || "".equals(user.getPassword().trim())
                || ud.loadByUsername(user.getUsername()) != null) {
            throw new OndocException("尊敬的用户您好，由于本系统的大量功能由JS实现，请取消禁用JS脚本");
        }

        User tempUser = new User();
        //设置默认头像
        tempUser.setHeadpic("img/0.jpg");
        tempUser.setUsername(user.getUsername());
        tempUser.setPassword(new MD5().getkeyBeanofStr(user.getPassword()));
        //TODO用正则表达式判断formUser.getTeleOrEmail()
        if (user.getTeleOrEmail().contains("@")) {
            tempUser.setEmail(user.getTeleOrEmail());
        } else {
            tempUser.setTele(user.getTeleOrEmail());
        }
        ud.add(tempUser);
        return "redirect:main";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:main";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String upload() {
        return "/user/UpInput";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(@RequestParam MultipartFile[] docu,
            HttpSession session, String[] name, String[] info,
            String[] p1, String[] p2, String[] p3) {

        Category rootCate = DefaultValue.ROOT_CATEGORY;
        User tempUser = (User) session.getAttribute("loginUser");
        String relativePath = "/WEB-INF/upload";
        String realPath = session.getServletContext().getRealPath(relativePath);
        //"E:\\codes\\java\\maven_springmvc_test\\src\\main\\webapp\\WEB-INF\\upload"
        for (int i = 0; i < docu.length; i++) {
            Category cate1 = DaoFactory.getCategoryDao().loadByName(p1[i]);
            Category cate2 = DaoFactory.getCategoryDao().loadByName(p2[i]);
            Category cate3 = DaoFactory.getCategoryDao().loadByName(p3[i]);
            if (cate1 == null || cate1.getIsVaild() == Category.IS_NOT_VAILD
                    || !cate1.getCateSet().contains(cate2) || cate2.getIsVaild() == Category.IS_NOT_VAILD
                    || !cate2.getCateSet().contains(cate3) || cate3.getIsVaild() == Category.IS_NOT_VAILD) {
                System.out.println("第" + (i + 1) + "个文件上传失败，分类选择不正确");
                continue;
            }

            //得到目标路径
            String fileName = docu[i].getOriginalFilename();
            if (name[i] == null || "".equals(name[i].trim())) {
            } else {
                String ext = fileName.substring(fileName.lastIndexOf("."));
                fileName = name[i] + ext;
            }
            String filePath = realPath + File.separator + fileName;
            try {
                File file = new File(filePath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                docu[i].transferTo(file);
                Document doc = new Document();
                doc.setName(fileName);
//                如果所有文档都没填简介，则info.length=0;此时不能用info[0]==null判断
                if (info.length == 0 || info[i] == null || "".equals(info[i].trim())) {
                } else {
                    doc.setInfo(info[i]);
                }
                doc.setUpUser(tempUser);
                doc.setPath(relativePath + "/" + fileName);
                doc.setCategory(cate3);
                tempUser.setUptotal(tempUser.getUptotal() + 1);
                rootCate.setDocuCount(rootCate.getDocuCount() + 1);
                cate1.setDocuCount(cate1.getDocuCount() + 1);
                cate2.setDocuCount(cate2.getDocuCount() + 1);
                cate3.setDocuCount(cate3.getDocuCount() + 1);
                bcd.update(cate1);
                bcd.update(cate2);
                bcd.update(cate3);
                bdd.add(doc);
            } catch (IOException | IllegalStateException ex) {
                Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("第" + (i + 1) + "个文件拷贝失败：" + ex.getMessage());
            }
        }
        return "redirect:/main";
    }

    /**
     * 处理下载
     *
     */
    @RequestMapping(value = "/document/{documentId}/download", method = RequestMethod.GET)
    public void download(@PathVariable int documentId, HttpServletRequest req, HttpSession session, HttpServletResponse res) {
        OutputStream os = null;
        Document docu = docuDao.load(documentId);
        if (docu == null) {
            throw new OndocException("请求资源错误，资源不存在");
        }
        try {
            os = res.getOutputStream();
            res.reset();
            String filename = docu.getName();
            if (req.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                filename = URLEncoder.encode(filename, "UTF-8");
            } else {
                filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
            }
            res.setHeader("Content-Disposition",
                    "attachment;filename=" + filename);
            res.setContentType("application/octet-stream;charset=utf-8");
            String realPath = session.getServletContext().getRealPath(docu.getPath());
            os.write(FileUtils.readFileToByteArray(new File(realPath)));
            os.flush();

            docu.setDowntotal(docu.getDowntotal() + 1);
            docuDao.update(docu);
            User user = (User) session.getAttribute("loginUser");
            user.setDowntotal(user.getDowntotal() + 1);
            ud.update(user);
        } catch (IOException ex) {
            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ex) {
                    Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    /**
     * 修改个人信息的唯一入口<br/>
     *
     * @return
     */
    @RequestMapping(value = "modifyInfo", method = RequestMethod.GET)
    public String modifyInfoInput(Model model, @ModelAttribute("loginUser") User loginUser) {
//        return "redirect:/main";
        return "/user/modifyInfoInput";
    }
    
    @RequestMapping(value = "modifyInfo", method = RequestMethod.POST)
    public String modifyInfo(ModifyInputDTO formUser, HttpSession session){
        //由于可以不修改用户信息，此时不往数据库更新数据
        boolean isModified = false;
        User tempUser = (User) session.getAttribute("loginUser");
        //修改头像
        if (!formUser.getPho().isEmpty()) {
            String fname = formUser.getPho().getOriginalFilename();
            //得到的路径有问题？有时末尾有/有时没有/
            String realPath = session.getServletContext().getRealPath("/upload/photo/avatar/");
            //realPath 的值好奇怪，有时候是...../avatar；有时候是...../avatar/；为了统一做处理
            if (realPath.length() - realPath.lastIndexOf(File.separator) > 1) {
                realPath += File.separator;
            }
            String fpath = realPath + tempUser.getId() + fname.substring(fname.lastIndexOf("."));

            //生成存放头像文件的文件夹
            File folder = new File(realPath);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            try {
                formUser.getPho().transferTo(new File(fpath));
                //将上传的图片文件转换成更小的缩略图，并覆盖原图片
                Thumb.thumbnailsProductor(fpath);
            } catch (IOException e) {
                System.out.println("UserAction--Me();上传头像失败");
                throw new OndocException("上传头像失败");
            }
            //页面获取图片的时候，upload前面不能有/
            isModified = true;
            tempUser.setHeadpic("upload/photo/avatar/" + tempUser.getId() + fname.substring(fname.lastIndexOf(".")));
        }

        //修改手机
        if (formUser.getTele() != null && !"".equals(formUser.getTele().trim())) {
            isModified = true;
            tempUser.setTele(formUser.getTele());
        }

        //修改邮箱
        if (formUser.getEmail() != null && !"".equals(formUser.getEmail().trim())) {
            isModified = true;
            tempUser.setEmail(formUser.getEmail());
        }

        //修改密码
        boolean modifyPassword = true;
        //"原密码"、"新密码"以及"确认新密码"均为空，则视为不修改密码，否则修改密码
        if ((formUser.getPassword() == null || "".equals(formUser.getPassword().trim()))
                && (formUser.getNewPassword() == null || "".equals(formUser.getNewPassword()))
                && (formUser.getNewPassword2() == null || "".equals(formUser.getNewPassword2()))) {
            modifyPassword = false;
        }
        if (modifyPassword) {
            //"原密码"、"新密码"以及"确认新密码"有一个为空，则提示错误信息
            if ((formUser.getPassword() == null || "".equals(formUser.getPassword().trim()))
                    || (formUser.getNewPassword() == null || "".equals(formUser.getNewPassword()))
                    || (formUser.getNewPassword2() == null || "".equals(formUser.getNewPassword2()))) {
                System.out.println("密码未修改，修改密码的信息未填写完整");
            } else if (!formUser.getNewPassword().equals(formUser.getNewPassword2())) {
                System.out.println("密码未修改，两次输入的新密码不一致");
            } else if (formUser.getNewPassword().equals(formUser.getPassword())) {
                System.out.println("密码未修改，输入的新密码与旧密码一致");
            } else if (!new MD5().getkeyBeanofStr(formUser.getPassword()).equals(tempUser.getPassword())) {
                System.out.println("密码未修改，输入的旧密码错误");
            } else {
                //满足两次输入新密码一致、旧密码匹配即可修改密码
                isModified = true;
                tempUser.setPassword(new MD5().getkeyBeanofStr(formUser.getNewPassword()));
            }
        }
        if (isModified) {
            ud.update(tempUser);
        }
        return "redirect:/main";
    }
    

}
